﻿using com.evaair.mall;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

/// <summary>
/// CommonUtil 共用模組
/// </summary>
public class CommonUtil
{
  /// <summary>
  /// 取得WebDevice
  /// </summary>
  public static string GetWebDevice()
  {
    return System.Configuration.ConfigurationManager.AppSettings["WebDeviceid"].ToString();
  }

  /// <summary>
  /// 由產品資料決定Banner
  /// </summary>
  /// <param name="Output_Prod_Cat_ID">0:一般、1:哩上加禮、2:紅配綠、3:限時折扣、4:期間限定</param>
  /// <param name="Prod_Cat_ID">產品所在館別ID，格式：(X館別IDX)</param>
  /// <param name="imgBanner">Banner圖片控制項</param>
  public static void GetBannerForProduct(string Output_Prod_Cat_ID, string Prod_Cat_ID, HtmlImage imgBanner)
  {
    if (imgBanner != null)
    {
      if (!string.IsNullOrEmpty(Output_Prod_Cat_ID))
      {
        switch (Output_Prod_Cat_ID)
        {
          case "0":
            if (!string.IsNullOrEmpty(Prod_Cat_ID))
            {
              string CurrentCatID = Prod_Cat_ID.Replace("(", "").Replace(")", "").Replace("X", "");
              string[] CatArray = CurrentCatID.Split(',');
              if (CatArray.Length > 0)
              {
                switch (CatArray[0].ToString().Substring(0, 1))
                {
                  case "1":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/EVA_AIR_ONLY.jpg";
                    break;
                  case "2":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/BOUTIQUE.jpg";
                    break;
                  case "3":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/ELECTRONIC.jpg";
                    break;
                  case "4":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/LIFE_STYLE.jpg";
                    break;
                  case "5":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/BEAUTY.jpg";
                    break;
                  case "6":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/GOURMET_FEAST.jpg";
                    break;
                  case "7":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/MILEAGES.jpg";
                    break;
                  case "8":
                    imgBanner.Src = "~/Images/banners/SimpleBanner/DISCOUNT.jpg";
                    break;
                  default:
                    imgBanner.Src = "~/Images/banners/SimpleBanner/EVA_AIR_ONLY.jpg";
                    break;
                }
              }
            }
            else
            {
              imgBanner.Src = "~/Images/banners/SimpleBanner/EVA_AIR_ONLY.jpg";
            }
            break;
          case "1":
            imgBanner.Src = "~/Images/banners/SimpleBanner/MILEAGES.jpg";
            break;
          case "2":
            imgBanner.Src = "~/Images/banners/SimpleBanner/DISCOUNT_Red_Green.jpg";
            break;
          case "3":
            imgBanner.Src = "~/Images/banners/SimpleBanner/simple6.jpg";
            break;
          case "4":
            imgBanner.Src = "~/Images/banners/SimpleBanner/Simple5.jpg";
            break;
        }
      }
      else
      {
        imgBanner.Src = "~/Images/banners/SimpleBanner/EVA_AIR_ONLY.jpg";
      }
    }
  }

  /// <summary>
  /// 取得商品為新品或是人氣的圖片資料
  /// </summary>
  /// <param name="LightStatus">商品狀態</param>
  /// <returns></returns>
  public static string GetNEWAndHOT(string LightStatus)
  {
    string status = string.Empty;
    string css = "hot";
    if (!string.IsNullOrEmpty(LightStatus))
    {
      var LightArray = LightStatus.Split(new Char[] { ',' });
      foreach (var light in LightArray)
      {
        switch (light)
        {
          case "人氣":
            css = "hot";
            break;
          case "新品":
            css = "new";
            break;
          case "促銷":
            css = "promo";
            break;
          case "破盤":
            css = "sale";
            break;
          case "獨家":
            css = "hot";
            break;
          case "限量":
            css = "new";
            break;
          case "嚴選":
            css = "promo";
            break;
        }
        status += "<span class=\"" + css + "\">" + light + "</span>";
      }
    }
    return status;
  }

  /// <summary>
  /// 儲存SiteMap的Dictionary至Cache
  /// </summary>  
  public static void GenericSiteMapList()
  {
    if (HttpContext.Current.Cache["SiteMapList"] == null)
    {
      Dictionary<string, PlaceHolder> SiteMapList = new Dictionary<string, PlaceHolder>();

      PlaceHolder SiteMapLiteral;
      HyperLink home;
      HyperLink firstLevel;

      B2C_MALL_Categories ws = new B2C_MALL_Categories();
      ws.Url = ConfigurationManager.AppSettings["B2C_MALL_Categories"].ToString();
      string jsonString = ws.B2C_MALL_GetCategories(CommonUtil.GetWebDevice()
        , HttpContext.Current.User.Identity.Name);
      JObject restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
      string Is_Valid = restoredObject["Is_Valid"].ToString();
      string msg = restoredObject["Msg"].ToString();
      if (Is_Valid == "Y")
      {
        JArray jArray = (JArray)restoredObject["PROD_CAT_Ary"];
        var results = jArray.Where(m => m["parent_id"].ToString() == "0").OrderBy(x => x["PROD_CAT_ID"]);
        foreach (var main in results)
        {
          SiteMapLiteral = new PlaceHolder();

          home = new HyperLink();
          home.Text = "首頁";
          home.NavigateUrl = "~/Home.aspx";
          SiteMapLiteral.Controls.Add(home);
          SiteMapLiteral.Controls.Add(new LiteralControl(" / "));
          firstLevel = new HyperLink();
          firstLevel.CssClass = "current";
          firstLevel.Text = main["PROD_CAT_TYPE"].ToString();
          switch (main["PROD_CAT_ID"].ToString())
          {
            case "7":
              firstLevel.NavigateUrl = "~/Products/ProductsListMileages.aspx?category=" + main["PROD_CAT_ID"].ToString();
              break;
            default:
              firstLevel.NavigateUrl = "~/Products/ProductsList.aspx?category=" + main["PROD_CAT_ID"].ToString();
              break;
          }            
          SiteMapLiteral.Controls.Add(firstLevel);
          SiteMapList.Add(main["PROD_CAT_ID"].ToString(), SiteMapLiteral);

          var secondResults = jArray
            .Where(m => m["parent_id"].ToString() == main["PROD_CAT_ID"].ToString());

          PlaceHolder secondSiteMapLiteral;
          HyperLink secondLevel;

          foreach (var second in secondResults)
          {
            secondSiteMapLiteral = new PlaceHolder();

            home = new HyperLink();
            home.Text = "首頁";
            home.NavigateUrl = "~/Home.aspx";
            secondSiteMapLiteral.Controls.Add(home);
            secondSiteMapLiteral.Controls.Add(new LiteralControl(" / "));
            firstLevel = new HyperLink();
            firstLevel.Text = main["PROD_CAT_TYPE"].ToString();
            switch (main["PROD_CAT_ID"].ToString())
            {
              case "7":
                firstLevel.NavigateUrl = "~/Products/ProductsListMileages.aspx?category=" + main["PROD_CAT_ID"].ToString();
                break;
              default:
                firstLevel.NavigateUrl = "~/Products/ProductsList.aspx?category=" + main["PROD_CAT_ID"].ToString();
                break;
            }            
            secondSiteMapLiteral.Controls.Add(firstLevel);
            secondSiteMapLiteral.Controls.Add(new LiteralControl(" / "));
            secondLevel = new HyperLink();
            secondLevel.CssClass = "current";
            secondLevel.Text = second["PROD_CAT_TYPE"].ToString();
            switch (second["PROD_CAT_ID"].ToString())
            {             
              case "7_1":
              case "7_2":
              case "7_3":
                secondLevel.NavigateUrl = "~/Products/ProductsListMileages.aspx?category=" + second["PROD_CAT_ID"].ToString();
                break;
              case "8_12":
                secondLevel.NavigateUrl = "~/Products/ProductsListClock.aspx?category=" + second["PROD_CAT_ID"].ToString();
                break;
              case "8_13":
                secondLevel.NavigateUrl = "~/Products/ProductsListPeriod.aspx?category=" + second["PROD_CAT_ID"].ToString();
                break;
              default:
                secondLevel.NavigateUrl = "~/Products/ProductsList.aspx?category=" + second["PROD_CAT_ID"].ToString();
                break;
            }
            
            secondSiteMapLiteral.Controls.Add(secondLevel);
            SiteMapList.Add(second["PROD_CAT_ID"].ToString(), secondSiteMapLiteral);

            var thirdResults = jArray.Where(m => m["parent_id"].ToString() == second["PROD_CAT_ID"].ToString());
            PlaceHolder thirdSiteMapLiteral;
            HyperLink thirdLevel;

            foreach (var third in thirdResults)
            {
              thirdSiteMapLiteral = new PlaceHolder();

              home = new HyperLink();
              home.Text = "首頁";
              home.NavigateUrl = "~/Home.aspx";
              thirdSiteMapLiteral.Controls.Add(home);
              thirdSiteMapLiteral.Controls.Add(new LiteralControl(" / "));
              firstLevel = new HyperLink();
              firstLevel.Text = main["PROD_CAT_TYPE"].ToString();
              firstLevel.NavigateUrl = "~/Products/ProductsList.aspx?category=" + main["PROD_CAT_ID"].ToString();
              thirdSiteMapLiteral.Controls.Add(firstLevel);
              thirdSiteMapLiteral.Controls.Add(new LiteralControl(" / "));
              secondLevel = new HyperLink();
              secondLevel.Text = second["PROD_CAT_TYPE"].ToString();
              secondLevel.NavigateUrl = "~/Products/ProductsList.aspx?category=" + second["PROD_CAT_ID"].ToString();
              thirdSiteMapLiteral.Controls.Add(secondLevel);

              thirdSiteMapLiteral.Controls.Add(new LiteralControl(" / "));
              thirdLevel = new HyperLink();
              thirdLevel.CssClass = "current";
              thirdLevel.Text = third["PROD_CAT_TYPE"].ToString();
              thirdLevel.NavigateUrl = "~/Products/ProductsList.aspx?category=" + third["PROD_CAT_ID"].ToString();
              thirdSiteMapLiteral.Controls.Add(thirdLevel);
              SiteMapList.Add(third["PROD_CAT_ID"].ToString(), thirdSiteMapLiteral);
            }
          }
        }
        int CacheDay = int.Parse(ConfigurationManager.AppSettings["SiteMapCacheDay"].ToString());
        HttpContext.Current.Cache.Insert("SiteMapList", SiteMapList, null
           , DateTime.Now.AddDays(CacheDay)
           , System.Web.Caching.Cache.NoSlidingExpiration);
      }
    }
  }

  /// <summary>
  /// 由信用卡別代號取得信用卡類型
  /// </summary>
  /// <param name="cardType">卡別代號</param>
  /// <returns>信用卡名稱</returns>
  public static string GetPayType(string cardType)
  {
    string CreditType = "VISA";
    switch (cardType)
    {
      case "1VI":
        CreditType = "VISA";
        break;
      case "1MT":
        CreditType = "MASTER CARD";
        break;
      case "1JC":
        CreditType = "JCB";
        break;
      case "1AX":
        CreditType = "AMERICAN EXPRESS";
        break;
      case "1DC":
        CreditType = "DINER CLUB";
        break;
      case "200":
        CreditType = "銀行匯款";
        break;
      case "500":
        CreditType = "國泰世華WEBATM";
        break;
    }
    return CreditType;
  }

  /// <summary>
  /// 哩上加哩館別使用之會員哩程卡別
  /// </summary>
  /// <param name="cardType">卡別代號</param>
  /// <returns>卡別名稱</returns>
  public static string GetEVACardType(string cardType)
  {
    string CreditType = "GC";
    switch (cardType)
    {
      case "GC":
        CreditType = "綠卡：GC";
        break;
      case "CE":
        CreditType = "銀卡：CE";
        break;
      case "CG":
        CreditType = "金卡：CG";
        break;
      case "CD":
        CreditType = "鑽石卡：CD";
        break;
    }
    return CreditType;
  }


  /// <summary>
  /// 取得會員獨享價
  /// </summary>
  /// <param name="MbrPrice">WS取回之會員價</param>
  /// <returns>處理判斷後的會員價</returns>
  public static string GetMemberPrice(string MbrPrice)
  {
    int finalPrice = 0;
    string result = string.Empty;
    if (!string.IsNullOrEmpty(MbrPrice) && MbrPrice != "0" && int.TryParse(MbrPrice, out finalPrice))
    {      
      result = "<p class=\"orange-text\">會員獨享價 $ <strong>"
        + finalPrice.ToString("n0")
        + "</strong></p>";
    }
    return result;
  }

  /// <summary>
  /// 取得訂單狀態
  /// </summary>
  /// <param name="Order_Status">訂單狀況編號</param>
  /// <returns>訂單狀號名稱</returns>
  public static string GetOrderStatus(string Order_Status)
  {
    string status = "處理中";
    switch (Order_Status)
    {
      case "0":
        status = "已取消";
        break;
      case "1":
        status = "已接單";
        break;
      case "2":
        status = "已出貨";
        break;
      case "3":
        status = "處理中";
        break;
    }
    return status;
  }

  public static string Utf16ToUtf8(string utf16String)
  {
    string utf8String = string.Empty;
    if (!string.IsNullOrEmpty(utf16String))
    {
      // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
      byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
      byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);
      // Return UTF8 bytes as ANSI string
      utf8String = Encoding.Default.GetString(utf8Bytes);
    }
    return utf8String;
  }


  public static string Utf16ToBIG5(string utf16String)
  {
    string big5String = string.Empty;
    if (!string.IsNullOrEmpty(utf16String))
    {
      // Get UTF16 bytes and convert UTF16 bytes to BIG5 bytes
      byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
      byte[] big5Bytes = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(950), utf16Bytes);
      // Return BIG5 bytes as ANSI string
      big5String = Encoding.Default.GetString(big5Bytes);
    }
    return big5String;
  }

  /// <summary>
  /// 轉換 ShoppingCart 物件為 OrderList 物件並且Serialize
  /// </summary>
  /// <param name="ShoppingCart">ShoppingCart</param>
  /// <returns>OrderList 序列化字串</returns>
  public static string ShoppingCartToOrderListSerialize(ShoppingCart sc)
  {
    string strOrderList = "";
    List<OrderList> liOrderList = new List<OrderList>();
    if (sc.CartItems.Count > 0)
    {
      foreach (CartItem ci in sc.CartItems)
      {
        OrderList ol = new OrderList();
        ol.B2C_CODE = ci.B2C_CODE;
        ol.SMAS_CODE = ci.SMAS_CODE;
        ol.Prod_Cat_ID = ci.Prod_Cat_ID;
        ol.QTY = ci.Quantity;
        ol.Type = ci.Type;
        ol.ProdCatID = ci.ProdCatID;
        liOrderList.Add(ol);
      }
      strOrderList= JsonConvert.SerializeObject(liOrderList);
    }
    return strOrderList;
  }

  /// <summary>
  /// 轉換 FreePlusList 物件為 FreePlusItem 物件並且Serialize
  /// </summary>
  /// <param name="List<FreePlusList>">FreePlusList List泛型</param>
  /// <returns>FreePlusItem 序列化字串</returns>
  public static string FreePlusListToFreePlusItemSerialize(List<FreePlusList> liFreePlusList)
  {
    string strFreePlusItem = "";
    List<FreePlusItem> liOrderList = new List<FreePlusItem>();
    if (liFreePlusList.Count > 0)
    {
      foreach (FreePlusList fpl in liFreePlusList)
      {
        FreePlusItem fpi = new FreePlusItem();
        fpi.B2C_CODE = fpl.B2C_CODE;
        fpi.SMAS_CODE = fpl.SMAS_CODE;
        fpi.Promotion_ID = fpl.Promotion_ID;
        fpi.Prd_Type = fpl.Prd_Type;
        liOrderList.Add(fpi);
      }
      strFreePlusItem = JsonConvert.SerializeObject(liOrderList);
    }
    return strFreePlusItem;
  }

  /// <summary>
  /// 將數字轉換為日期格式
  /// </summary>
  /// <param name="yyyyMMdd">20150101</param>
  /// <returns>2015/01/01</returns>
  public static string TransferyyyyMMddToDate(string yyyyMMdd)
  {
    string dateString = yyyyMMdd;
    if (!string.IsNullOrEmpty(dateString))
    {
      int result = 0;
      if (dateString.Length == 8 && int.TryParse(dateString, out result))
      {
        dateString = dateString.Substring(0, 4) + "/" +
                      dateString.Substring(4, 2) + "/" +
                      dateString.Substring(6, 2);
        DateTime date;
        if (!DateTime.TryParse(dateString, out date))
        {
          dateString = "9999/12/31";
        }        
      }
    }
    return dateString;
  }

  /// <summary>
  /// 將數字轉換為時間格式
  /// </summary>
  /// <param name="hhmmss">010101</param>
  /// <returns>01:01:01</returns>
  public static string TransferhhmmssToTime(string hhmmss)
  {
    string TimeString = hhmmss;
    if (!string.IsNullOrEmpty(TimeString))
    {
      int result = 0;
      if (TimeString.Length == 6 && int.TryParse(TimeString, out result))
      {
        TimeString = TimeString.Substring(0, 2) + ":" +
                      TimeString.Substring(2, 2) + ":" +
                      TimeString.Substring(4, 2);        
      }
    }
    return TimeString;
  }

  /// <summary>
  /// 取得Request的Form或QueryString值
  /// </summary>
  /// <param name="strItem">傳入KEY值</param>
  /// <returns>回傳結果</returns>
  public static string GetRequestValue(string strItem)
  {
    string data = HttpContext.Current.Request[strItem];
    if (!string.IsNullOrEmpty(data))
    {
      return HttpContext.Current.Server.HtmlEncode(data).Trim().Replace(",", "").Replace("%", "");  
    }
    else
    {
      return "";
    }
  }

}